import { listAllFactorys, listPermitFactory } from "@/api/factory";
// 粒度
const GRANULARITY = [
  // "workSectionId",
  // "workSectionCode",
  "lineId",
  "lineCode",
  "workshopId",
  "workshopCode",
  "factoryDeptId",
  "factoryDeptCode",
];
class WorkTree {
  data = [];
  flattenData = [];
  permission = {};
  hasPermission = false;
  loaded = false;
  /**
   * 创建实例时，传入是否有权限控制参数
   * @param {*} hasPermission 是否有权限控制
   */
  constructor(hasPermission = false) {
    this.data = [];
    this.flattenData = [];
    this.loaded = false;
    this.hasPermission = hasPermission;
  }
  getData() {
    if (this.hasPermission) {
      return Promise.all([listAllFactorys(), listPermitFactory()])
        .then(([res1, res2]) => {
          this.data = res1?.data || [];
          this.permission = res2?.data || {};

          this.flattenData = this.getFlattenData(res1?.data || []);
          this.loaded = true;
        })
        .catch(() => {
          this.data = [];
          this.permission = {};

          this.flattenData = [];
          this.loaded = true;
        });
    } else {
      return Promise.all([listAllFactorys()])
        .then(([res1]) => {
          this.data = res1?.data || [];
          this.flattenData = this.getFlattenData(res1?.data || []);
          this.loaded = true;
        })
        .catch(() => {
          this.data = [];
          this.flattenData = [];
          this.loaded = true;
        });
    }
  }
  getFlattenData = (treeData) => {
    const hasPermi = this.hasPermission;
    const permission = this.permission;
    let result = [];
    treeData.forEach((factory) => {
      if (
        (hasPermi &&
          permission.permitFactoryIds.includes(factory.factoryDeptId)) ||
        !hasPermi
      ) {
        result.push({ ...factory, type: "factory" });
        if (factory.workshopVos?.length) {
          factory.workshopVos.forEach((workshop) => {
            if (
              (hasPermi &&
                permission.permitWorkshopIds.includes(workshop.workshopId)) ||
              !hasPermi
            ) {
              result.push({ ...workshop, parent: factory, type: "workshop" });
              if (workshop.productionLineVos?.length) {
                workshop.productionLineVos.forEach((productionLine) => {
                  if (
                    (hasPermi &&
                      permission.permitLineIds.includes(
                        productionLine.lineId
                      )) ||
                    !hasPermi
                  ) {
                    result.push({
                      ...productionLine,
                      parent: workshop,
                      type: "productionLine",
                    });
                    if (productionLine.workStationVos?.length) {
                      productionLine.workStationVos.forEach((workStation) => {
                        result.push({
                          ...workStation,
                          parent: productionLine,
                          type: "workStation",
                        });
                      });
                    }
                  }
                });
              }
            }
          });
        }
      }
    });
    return result;
  };
  // 创建实例后，调用affterLoad后开始执行业务场景的代码
  async affterLoad() {
    await this.getData();
    return Promise.resolve();
  }
  // 获取工厂
  getFactory() {
    return this.flattenData.filter((ele) => ele.type === "factory");
  }
  // 获取车间，优先根据factoryDeptId匹配，没有则按factoryCode匹配，都没有返回所有车间
  getWorkshop(searchObj = {}) {
    if (Object.prototype.toString.call(searchObj) == "[object Function]") {
      return this.flattenData.filter(
        (ele) => ele.type === "workshop" && searchObj(ele)
      );
    }
    const key = this.getMinGranularity(searchObj);
    if (key) {
      return this.flattenData.filter(
        (ele) => ele.type === "workshop" && ele[key] === searchObj[key]
      );
    }
    return this.flattenData.filter((ele) => ele.type === "workshop");
  }
  // 获取产线，规则与上同理
  getProductionLine(searchObj = {}) {
    if (Object.prototype.toString.call(searchObj) == "[object Function]") {
      return this.flattenData.filter(
        (ele) => ele.type === "productionLine" && searchObj(ele)
      );
    }
    const key = this.getMinGranularity(searchObj);
    if (key) {
      return this.flattenData.filter(
        (ele) => ele.type === "productionLine" && ele[key] === searchObj[key]
      );
    }
    return this.flattenData.filter((ele) => ele.type === "productionLine");
  }
  // 获取工序，规则与上同理
  getWorkSection(searchObj = {}) {
    if (Object.prototype.toString.call(searchObj) == "[object Function]") {
      return this.flattenData.filter(
        (ele) => ele.type === "workSection" && searchObj(ele)
      );
    }
    const key = this.getMinGranularity(searchObj);
    if (key) {
      return this.flattenData.filter(
        (ele) => ele.type === "workSection" && ele[key] === searchObj[key]
      );
    }
    return this.flattenData.filter((ele) => ele.type === "workSection");
  }
  // 获取工位，规则与上同理
  getWorkStation(searchObj = {}) {
    if (Object.prototype.toString.call(searchObj) == "[object Function]") {
      return this.flattenData.filter(
        (ele) => ele.type === "workStation" && searchObj(ele)
      );
    }
    const key = this.getMinGranularity(searchObj);
    if (key) {
      return this.flattenData.filter(
        (ele) => ele.type === "workStation" && ele[key] === searchObj[key]
      );
    }
    return this.flattenData.filter((ele) => ele.type === "workStation");
  }
  // 获取最小粒度字段
  getMinGranularity(searchObj) {
    let key = "";
    for (let i = 0; i < GRANULARITY.length; i++) {
      const ele = GRANULARITY[i];
      if (searchObj[ele]) {
        key = ele;
        break;
      }
    }
    return key;
  }
}

export default WorkTree;
